<?php
/**
 * Copyright (c) Enalean, 2017. All Rights Reserved.
 *
 * This file is a part of Tuleap.
 *
 * Tuleap is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Tuleap is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Tuleap. If not, see <http://www.gnu.org/licenses/>.
 */

namespace Tuleap\Cryptography\Asymmetric;

use Tuleap\Cryptography\Exception\InvalidSignatureException;

final class AsymmetricCrypto
{
    public function __construct()
    {
        throw new \RuntimeException('Do not instantiate this class, invoke the static methods directly');
    }

    /**
     * @return string
     */
    public static function sign($message, SignatureSecretKey $secret_key)
    {
        if (! is_string($message)) {
            throw new \TypeError('Expected $message to be a string, got ' . gettype($message));
        }

        return \sodium_crypto_sign_detached($message, $secret_key->getRawKeyMaterial());
    }

    /**
     * @return bool
     * @throws InvalidSignatureException
     */
    public static function verify($message, SignaturePublicKey $public_key, $signature)
    {
        if (! is_string($message)) {
            throw new \TypeError('Expected $message to be a string, got ' . gettype($message));
        }
        if (! is_string($signature)) {
            throw new \TypeError('Expected $signature to be a string, got ' . gettype($signature));
        }
        if (\mb_strlen($signature, '8bit') !== SODIUM_CRYPTO_SIGN_BYTES) {
            throw new InvalidSignatureException('Signature must be SODIUM_CRYPTO_SIGN_BYTES long');
        }

        return \sodium_crypto_sign_verify_detached($signature, $message, $public_key->getRawKeyMaterial());
    }
}
